import {useImmerState} from '../../hooks/useImmerState';
import * as memberApi from '../../apis/member';
import useGlobal from '../../hooks/useGlobal';

const useMemberListModel = (initialState = {
  waitList: [],
  passList: [],
  rejectList: [],
  quitList: [],
  allList: []
}) => {
  const [state, setState] = useImmerState(initialState);
  const {state: globalState} = useGlobal();

  const getMemberList = async () => {
    const list = await memberApi.getList(globalState.login?.token || '');
    if (list.length) {
      setState(() => {
        const _list = {
          waitList: [],
          passList: [],
          rejectList: [],
          quitList: [],
          allList: []
        };
        list.forEach(item => {
          item.key = item.id;
          if (item.status === 2) {
            _list.waitList.push(item);
          } else if (item.status === 1) {
            _list.passList.push(item);
          } else if (item.status === 0) {
            _list.rejectList.push(item);
          } else if (item.status === 4) {
            _list.quitList.push(item);
          }
          if (item.status !== 3) {
            _list.allList.push(item);
          }
        });
        return _list;
      });
    }
  };

  const editMember = async (detail) => {
    const res = await memberApi.update(globalState.login?.token || '', detail);
    if (res.data.code === 1) {
      getMemberList();
    }
  };

  const memberQuit = async userId => {
    const res = await memberApi.quit(globalState.login?.token || '', userId);
    if (res.data.code === 1) {
      // 离退成功
      getMemberList();
    }
  };

  const effect = {
    getMemberList,
    editMember,
    memberQuit
  };

  return {
    state,
    effect
  };
};

export default useMemberListModel;